var nodegit = require('nodegit'),
    path = require('path'),
    remoteRepo = 'git@git.oschina.net:tommas/test-repo.git',
    publicKey = './.ssh/id_rsa.pub',
    privateKey = './.ssh/id_rsa';

nodegit.Repository.open(__dirname + path.sep + 'test-repo/.git')
    .then(function(repo) {
        console.log('open repository');
        return repo;
    }, function(reason) {
        console.log(reason);
        console.log('clone repository');
        return nodegit.Clone.clone(remoteRepo, __dirname + path.sep + 'test-repo', {
            fetchOpts: {
                callbacks: {
                    certificateCheck: function() {
                        // for OSX
                        return 1;
                    },
                    credentials: function(url, username) {
                        console.log('url: ' + url);
                        console.log('username: ' + username);
                        return nodegit.Cred.sshKeyNew(username, publicKey, privateKey, '');;
                    }
                }
            }
        });
    })
    .then(function(repo) {
        console.log('open success');
        return repo.getStatus()
            .then(function(statusFiles) {
                console.log('get status');
                return repo.openIndex()
                    .then(function(index) {
                        if (!statusFiles.length) {
                            return index;
                        }

                        index.read(1);
                        return index.addAll()
                            .then(function() {
                                console.log('addAll');
                                index.write();
                                return index.writeTree()
                                    .then(function(oidResult) {
                                        var oid = oidResult;
                                        return repo.getHeadCommit()
                                            .then(function(parent) {
                                                return repo.createCommit('HEAD', undefined, undefined, 'fist commit', oid, [parent])
                                                    .then(function(commitId) {
                                                        console.log('new commit:' + commitId);
                                                        return index;
                                                    });
                                            });
                                    });
                            });
                    });
            });
    })
    .catch(function(error) {
        console.log(error);
    });
